<?php
/**
 * 新增角色类
 * User: Administrator
 * Date: 2018\8\31 0031
 * Time: 11:21
 */

namespace app\Lib\Model\Role\RoleManage;


use app\Lib\Exception\BlException;
use app\Lib\Exception\SysException;
use app\Lib\InterfaceIn\Role\RoleManage\AddRoleHandle;
use app\Lib\Model\DbModel\AdminRoleAuth;

class AddRole extends RoleOperatingBase implements AddRoleHandle
{

    /**
     * 执行代码
     * @return bool
     * @throws BlException
     * @throws SysException
     */
    public function run()
    {
        $model        = $this->getRoleDb();
        $roleValidate = $this->getRoleValidate();
        $data         =  $this->getHandleArray();
        $data[$model->_create_time] = time();
        $data[$model->_create_uid]  = $this->user->getUid();
        if(!$roleValidate->scene('add')->check($data)){
            throw new BlException($roleValidate->getError());
        }
        if(!$result = $model->insert($data,false,true)){
            throw new SysException('新增角色失败');
        }
        if(empty($this->authMenu)){
            return true;
        }
        $adminAuth = (new AdminRoleAuth());
        foreach ($this->authMenu as $ke=>$v){
            $newData[$ke] =[
                $adminAuth->_role_id=>$result,
                $adminAuth->_menu_id=>$v,
                $adminAuth->_create_uid=>$this->user->getUid(),
                $adminAuth->_create_time=>time(),
            ];
        }
        $authResult = $adminAuth->insertAll($newData);
        if(!$authResult){
            throw new SysException('角色授权失败');
        }
        return true;
    }

}